package com.example.plugin_native.createFarm

import android.Manifest
import android.app.Activity
import android.content.pm.PackageManager
import android.view.View
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.GridLayoutManager
import com.example.plugin_native.R
import com.example.plugin_native.adapter.FarmTypeRcvAdapter
import com.example.plugin_native.databinding.ActivityCreateFarmBinding
import com.example.plugin_native.databinding.DialogCreateFarmBottomBinding
import com.example.plugin_native.entity.PlotInfoData
import com.map.tiandimap.MapView
import com.map.utils.MapUtils
import com.map.interfaces.*
import com.support.base.DataBindingActivity
import com.support.base.equals
import com.support.base.set
import java.lang.StringBuilder

/**
 * zhang jun fei
 */
class CreateFarmActivity : DataBindingActivity<CreateFarmModel, ActivityCreateFarmBinding>(),
    View.OnClickListener {

    //请求的所有地块的点,默认为空
    private var plotInfoList: ArrayList<PlotInfoData>? = null

    //权限请求code
    private val requestCode = 100

    //切换当前位置展示
    private var toggleLocation = true

    //地图实例
    private lateinit var mapView: MapView

    //地图控制类
    private lateinit var mapControl: MapControl

    //地图是否加载完成
    private var isLoadComplete = false

    //地块面积
    private var area: String = "0"

    //绑定视图
    override fun bindLayout(): Int = R.layout.activity_create_farm


    /**
     * 视图初始化
     */
    override fun initView() {
        super.initView()
        binding.model = viewModel
        mapView = binding.mvMapView
        mapControl = MapControl(mapView)
        //地图加载完成的监听
        mapView.setOnMapLoadListener(object : OnMapLoadComplete {
            override fun onComplete() {
//                showToast("地图加载完成")
                //加载数据
                viewModel.getPlotInfo()
            }
        })
    }

    /**
     * 监听初始化
     */
    override fun initListener() {
        super.initListener()
        binding.ivLocation.setOnClickListener(this)
        binding.ivBack.setOnClickListener(this)
        binding.tvStartOver.setOnClickListener(this)
        binding.tvClose.setOnClickListener(this)
        binding.llRevocation.setOnClickListener(this)
        binding.tvCancel.setOnClickListener(this)
        binding.llRecover.setOnClickListener(this)
        binding.ivExpanded.setOnClickListener(this)
        binding.tvPackUp.setOnClickListener(this)
        binding.tvGuidebook.setOnClickListener(this)
    }

    /**
     * 数据初始化
     */
    override fun initData() {
        super.initData()
        //获取定位权限
        getPermission()
        //获取农场地块信息
        viewModel.plotInfoLiveData.observe(this) {
            isLoadComplete = true
            plotInfoList = it
            mapView.setCenter(it[0].points[0].lng, it[0].points[0].lat, zoom = 15)
            drawOtherArea()
        }

        //农场人员信息列表
        viewModel.principalLiveData.observe(this) { principals ->
            val menus = principals.map {
                it.userName
            }.toTypedArray()

            showBottomMenu(menus) {
                if (it.isNotEmpty()) {
                    val stringBuilder = StringBuilder()
                    viewModel.farmPrincipalList.clear()
                    it.forEach { index ->
                        stringBuilder.append("、").append(principals[index].userName)
                        viewModel.farmPrincipalList.add(principals[index].userPin)
                    }
                    viewModel.farmPrincipal.value = stringBuilder.substring(1)
                }
            }
        }

        //获取地块类型
        viewModel.plotTypeLiveData.observe(this) { plotTypes ->

            showBottomView<DialogCreateFarmBottomBinding>(R.layout.dialog_create_farm_bottom) { dialog, binding ->

                binding.model = viewModel

                //设置地块面积
                "${String.format("%.2f", area.toDouble() / 666.7)} 亩".also {
                    binding.tvArea.text = it
                }

                //取消
                binding.tvCancel.setOnClickListener {
                    //点击弹框取消，还原数据
                    viewModel.createFarmName = ""//名称
                    viewModel.farmPrincipal.value = "请选择"//选择的人员
                    viewModel.farmPrincipalList.clear()//选择的人员的id列表，提交的入参
                    viewModel.selectFarmColor.value = "#EE6C4B"//还原初始选择的颜色
                    viewModel.selectFarmColorLiveData set "#229B60"//还原画的地块的颜色
                    viewModel.selectFarmTypeIndex = 0//地块类型选择默认的index为0，用于缓存数据使用的
                    //地块类型，默认选择的状态为index为0的值
                    plotTypes.forEachIndexed { index, plotType ->
                        plotType.isSelect = index == 0
                    }
                    dialog.dismiss()
                }
                //提交
                binding.tvOk.setOnClickListener {
                    val name = viewModel.createFarmName
                    if (name.isEmpty()) {
                        showAlert(msg = "请输入地块名称")
                        return@setOnClickListener
                    }

                    if (viewModel.farmPrincipalList.isEmpty()) {
                        showAlert(msg = "请选择地块负责人")
                        return@setOnClickListener
                    }

                    viewModel.addPlot(
                        plotName = name,
                        plotArea = String.format(
                            "%.2f",
                            area.toDouble() / 666.7
                        ).toDouble()
                    )
                    dialog.dismiss()
                }
                //选择地块负责人
                binding.tvPrincipal.setOnClickListener {
                    viewModel.findFarmUsers()
                }
                //地块标记
                binding.tvMark.setOnClickListener {
                    val menu = viewModel.farmMark.values.toTypedArray()
                    showSingleSelectMenu(
                        menu,
                        selectIndex = viewModel.selectMark.value.first
                    ) {
                        viewModel.selectMark.value =
                            viewModel.farmMark.keys.toList()[it] to viewModel.farmMark.values.toList()[it]

                    }
                }
                val adapter = FarmTypeRcvAdapter(plotTypes)
                binding.rcvFarmType.layoutManager = GridLayoutManager(this, 4)
                binding.rcvFarmType.adapter = adapter
                adapter.setOnItemClickListener { _, _, _, position ->
                    plotTypes.forEachIndexed { index, plotType ->
                        plotType.isSelect = index == position
                    }
                    viewModel.selectFarmType = plotTypes[position].plotType
                    viewModel.selectFarmTypeIndex = position
                    adapter.notifyDataChanged(plotTypes)
                }
            }
        }

        //添加地块结果
        viewModel.isAddPlotSuc.observe(this) {
            if (it) {
                setResult(Activity.RESULT_OK)
                finish()
            }
        }

        //选择颜色改变地块颜色
        viewModel.selectFarmColorLiveData.observe(this) {
            mapView.clearAllLayer()
            drawOtherArea()
            mapControl.drawArea(
                mapControl.linePoints,
                tag = mapControl.newFarmTag,
                fillColor = it,
            )
        }
    }

    /**
     * 画的地块与其他地块是否有重叠
     */
    private fun isOverlap(points: List<Point>): Boolean {
        for (plotInfoData in plotInfoList!!) {
            for (point in plotInfoData.points) {
                if (MapUtils.isPolygonContainsPoint(points, point)) {
                    return true
                }
            }
            for (point in points) {
                if (MapUtils.isPolygonContainsPoint(plotInfoData.points, point)) {
                    return true
                }
            }
        }
        return false
    }

    /**
     * 画出原有地块
     */
    private fun drawOtherArea() {
        plotInfoList?.forEach { info ->
            mapControl.drawArea(
                info.points,
                color = "#00C286",
                opacity = 0.5f,
                fillColor = "#229B60",
                fillOpacity = 0.2f,
                isEdit = false
            )
        }
    }

    /**
     * 点击事件监听
     */
    override fun onClick(v: View?) {
        when (v) {
            //新手教程
            binding.tvGuidebook -> {
                ShowGuidebook().show(this)
            }
            //取消
            binding.tvCancel -> {
                if (viewModel.startAndOverText equals "开始绘制") {
                    finish()
                    return
                }
                mapView.clearAllLayer()
                drawOtherArea()
                viewModel.alertInfo set viewModel.stepOne
                viewModel.startAndOverText set "开始绘制"
                viewModel.startAndOverBtn set true
                viewModel.revocationBtn set false
                viewModel.recoverBtn set false
                mapControl.linePoints.clear()
                mapControl.registerPoints.clear()
                mapView.removeMapClick()
            }
            binding.ivBack -> {
                finish()
            }
        }
        if (!isLoadComplete) {
            return
        }
        when (v) {
            //提示收起
            binding.tvPackUp -> {
                binding.llInfo.visibility = View.GONE
                binding.vWeight.visibility = View.VISIBLE
            }
            //展开提示
            binding.ivExpanded -> {
                binding.llInfo.visibility = View.VISIBLE
                binding.vWeight.visibility = View.GONE
            }
            //恢复
            binding.llRecover -> {
                mapControl.recover()
                drawOtherArea()
                //可恢复的点为0的时候，不可点击
                if (mapControl.registerPoints.size == 0) {
                    viewModel.recoverBtn set false
                }
                if (mapControl.linePoints.size > 0) {
                    viewModel.revocationBtn set true
                }
                if (mapControl.linePoints.size >= 3) {
                    viewModel.alertInfo set viewModel.stepThree
                    viewModel.closeBtn set true
                }
            }
            //撤销
            binding.llRevocation -> {
                mapControl.revocation()
                drawOtherArea()
                //如果有撤销的点，则恢复按钮可点击
                if (mapControl.registerPoints.size > 0) {
                    viewModel.recoverBtn set true
                }
                //剩余的点少于三个，闭合不可点击
                if (mapControl.linePoints.size < 3) {
                    viewModel.alertInfo set viewModel.stepTwo
                    viewModel.closeBtn set false
                }
                //所有点已被撤销，撤销按钮置为不可点击
                if (mapControl.linePoints.size == 0) {
                    viewModel.revocationBtn set false
                }
            }
            //闭合
            binding.tvClose -> {
                mapView.clearAllLayer()
                drawOtherArea()
                viewModel.alertInfo set viewModel.stepFour
                mapView.removeMapClick()
                mapControl.drawArea(mapControl.linePoints, tag = mapControl.newFarmTag)
                viewModel.closeBtn set false
                viewModel.revocationBtn set false
                viewModel.recoverBtn set false
                viewModel.startAndOverBtn set true
            }
            //开始or完成
            binding.tvStartOver -> {
                //开始绘制
                if (viewModel.startAndOverText equals "开始绘制") {
                    viewModel.alertInfo set viewModel.stepTwo
                    mapView.setOnMapClickListener(object : OnMapClick {
                        override fun onClick(lng: Double, lat: Double) {
                            mapControl.drawLine(lng, lat) {
                                //当圈地闭合的时候调用
                                drawOtherArea()
                                viewModel.alertInfo set viewModel.stepFour
                                mapView.removeMapClick()
                                viewModel.closeBtn set false
                                viewModel.revocationBtn set false
                                viewModel.recoverBtn set false
                                viewModel.startAndOverBtn set true
                            }
                            //只要从新点击地图，恢复则不可用
                            viewModel.recoverBtn set false
                            //设置闭合按钮可点击
                            if (mapControl.linePoints.size >= 3) {
                                viewModel.closeBtn set true
                                viewModel.alertInfo set viewModel.stepThree
                            }
                            //设置撤销按钮可点击
                            if (mapControl.linePoints.size >= 1) {
                                viewModel.revocationBtn set true
                            }
                        }
                    })
                    //按钮是否可点击
                    viewModel.startAndOverBtn set false
                    //按钮展示的文字
                    viewModel.startAndOverText set "完成圈地"
                } else {
                    //完成绘制
                    //获取地块的经纬度的点
                    mapView.geAreaPointsByTag(
                        tag = mapControl.newFarmTag,
                        getAreaPoints = object : GetAreaPoints {
                            override fun points(points: List<Point>) {
                                if (isOverlap(points)) {
                                    showAlert("警告", "绘制地块与其他地块有重叠", "知道了")
                                    return
                                }

                                if (MapUtils.isCross(points)) {
                                    showAlert("警告", "绘制地块边有交叉", "知道了")
                                    return
                                }
                                mapControl.linePoints.apply {
                                    clear()
                                    addAll(points)
                                }
                                viewModel.setPlotPosition(points)
                                //获取地块的面积
                                mapView.getPolygonArea(points, object : GetArea {
                                    override fun area(area: String) {
                                        this@CreateFarmActivity.area = area
                                        //获取地块类型
                                        viewModel.getPlotTypes()
                                    }
                                })
                            }
                        })
                }
            }
            //定位
            binding.ivLocation -> {
                if (toggleLocation) {
                    mapView.location()
                } else {
                    mapView.setCenter(
                        plotInfoList!![0].points[0].lng,
                        plotInfoList!![0].points[0].lat,
                        zoom = 15
                    )
                }
                toggleLocation = !toggleLocation
            }
        }
    }

    //---------------------------------------------------------------------------------------------
    /**
     * 获取用户权限
     */
    private fun getPermission() {
        val permissions = mutableListOf<String>()
        //定位相关
        if (ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.ACCESS_FINE_LOCATION
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            val permissionStr = Manifest.permission.ACCESS_FINE_LOCATION
            permissions.add(permissionStr)
        }

        if (permissions.isNotEmpty()) {
            //如果用户拒绝了权限,shouldShowRequestPermissionRationale返回true
            if (ActivityCompat.shouldShowRequestPermissionRationale(
                    this,
                    Manifest.permission.ACCESS_FINE_LOCATION
                )
            ) {
                ActivityCompat.requestPermissions(this, permissions.toTypedArray(), requestCode)
            } else { //如果用户拒绝了权限，并勾选了不再询问
                ActivityCompat.requestPermissions(this, permissions.toTypedArray(), requestCode)
            }
        }
    }

    /**
     * 请求权限回调
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String?>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when (requestCode) {
            this.requestCode -> {

            }
        }
    }
}